import apiClient from "../apiClient";

enum Api {
	Upload = "/common/upload",
	AttachmentList = "/general/attachment/index",
	AttachmentCategory = "/general/attachment/category",
	CategoryList = "/general/attachment_category/index",
	CategoryAdd = "/general/attachment_category/add",
	CategoryEdit = "/general/attachment_category/edit",
	CategoryDelete = "/general/attachment_category/del",
	AttachmentSave = "/general/attachment/save",
	AttachmentDelete = "/general/attachment/del",
}

interface CategoryItem {
	id: number;
	name: string;
	createtime: number;
	updatetime: number;
	sort: number;
	status: string;
}

interface CategoryListResponse {
	total: number;
	items: CategoryItem[];
}

interface SaveAttachmentData {
	name: string;
	url: string;
	category_id?: number;
}

class CommonService {
	/**
	 * 上传单个文件
	 * @param file 文件对象
	 * @returns 返回文件URL
	 */
	async uploadFile(file: File) {
		const formData = new FormData();
		formData.append("file", file);
		return apiClient.post<string>({
			url: Api.Upload,
			data: formData,
			headers: {
				"Content-Type": "multipart/form-data",
			},
		});
	}

	/**
	 * 获取附件列表
	 * @param params 查询参数
	 */
	async getAttachmentList(params?: Record<string, any>) {
		return apiClient.get({
			url: Api.AttachmentList,
			params,
		});
	}

	/**
	 * 获取附件分类
	 */
	async getAttachmentCategory() {
		return apiClient.get({
			url: Api.AttachmentCategory,
		});
	}

	/**
	 * 获取分类列表
	 */
	async getCategoryList() {
		const response = await apiClient.get<CategoryListResponse>({
			url: Api.CategoryList,
		});
		return response.items;
	}

	/**
	 * 添加分类
	 */
	async addCategory(data: { name: string }) {
		return apiClient.post({
			url: Api.CategoryAdd,
			data,
		});
	}

	/**
	 * 编辑分类
	 */
	async editCategory(data: { id: number; name: string }) {
		return apiClient.post({
			url: Api.CategoryEdit,
			data,
		});
	}

	/**
	 * 删除分类
	 */
	async deleteCategory(id: number) {
		return apiClient.post({
			url: Api.CategoryDelete,
			data: { id },
		});
	}

	/**
	 * 删除附件
	 */
	async deleteAttachment(id: number) {
		return apiClient.post({
			url: Api.AttachmentDelete,
			data: { id },
		});
	}

	/**
	 * 保存附件
	 */
	async saveAttachment(data: SaveAttachmentData) {
		return apiClient.post({
			url: Api.AttachmentSave,
			data,
		});
	}
}

export const commonService = new CommonService();
